<template>
  <div class="template-manager">
    <!-- 操作工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-input
          v-model="searchForm.templateName"
          placeholder="搜索模板名称"
          size="small"
          style="width: 200px;"
          @input="loadTemplateList"
        >
          <i slot="prefix" class="el-input__icon el-icon-search"></i>
        </el-input>
        <el-select
          v-model="searchForm.campusId"
          placeholder="选择校区"
          size="small"
          style="width: 150px; margin-left: 10px;"
          @change="loadTemplateList"
          clearable
        >
          <el-option label="通用模板" :value="null" />
          <el-option
            v-for="campus in campusList"
            :key="campus.campusId"
            :label="campus.campusName"
            :value="campus.campusId"
          />
        </el-select>
      </div>
      <div class="toolbar-right">
        <el-button @click="showSaveDialog" type="primary" size="small">
          <i class="el-icon-plus"></i>
          保存当前为模板
        </el-button>
        <el-button @click="loadTemplateList" type="default" size="small">
          <i class="el-icon-refresh"></i>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 模板列表 -->
    <div class="template-list">
      <el-table
        :data="templateList"
        v-loading="loading"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="templateName" label="模板名称" min-width="150">
          <template slot-scope="scope">
            <div class="template-name">
              <span>{{ scope.row.templateName }}</span>
              <el-tag v-if="scope.row.isActive" type="success" size="mini">已启用</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="templateDesc" label="模板描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="campusId" label="所属校区" width="120">
          <template slot-scope="scope">
            {{ getCampusName(scope.row.campusId) }}
          </template>
        </el-table-column>
        <el-table-column prop="createBy" label="创建者" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="220" fixed="right">
          <template slot-scope="scope">
            <el-button-group>
              <el-button
                type="primary"
                size="mini"
                @click="loadTemplate(scope.row)"
              >
                <i class="el-icon-download"></i>
                加载
              </el-button>
              <el-button
                v-if="!scope.row.isActive"
                type="success"
                size="mini"
                @click="activateTemplate(scope.row)"
              >
                <i class="el-icon-check"></i>
                启用
              </el-button>
              <el-button
                type="info"
                size="mini"
                @click="copyTemplate(scope.row)"
              >
                <i class="el-icon-copy-document"></i>
                复制
              </el-button>
              <el-button
                type="danger"
                size="mini"
                @click="deleteTemplate(scope.row)"
              >
                <i class="el-icon-delete"></i>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchForm.pageNum"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="searchForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px; text-align: center;"
      />
    </div>

    <!-- 批量操作 -->
    <div class="batch-operations" v-if="selectedTemplates.length > 0">
      <span>已选择 {{ selectedTemplates.length }} 个模板</span>
      <el-button
        type="danger"
        size="small"
        @click="batchDelete"
        style="margin-left: 10px;"
      >
        批量删除
      </el-button>
    </div>

    <!-- 保存模板弹窗 -->
    <el-dialog title="保存为模板" :visible.sync="saveDialogVisible" width="500px">
      <el-form :model="saveForm" :rules="saveRules" ref="saveForm" label-width="100px">
        <el-form-item label="模板名称" prop="templateName">
          <el-input v-model="saveForm.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述" prop="templateDesc">
          <el-input
            type="textarea"
            v-model="saveForm.templateDesc"
            placeholder="请输入模板描述"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="所属校区" prop="campusId">
          <el-select v-model="saveForm.campusId" placeholder="选择校区" style="width: 100%;" clearable>
            <el-option label="通用模板（所有校区可用）" :value="null" />
            <el-option
              v-for="campus in campusList"
              :key="campus.campusId"
              :label="campus.campusName"
              :value="campus.campusId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveTemplate" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 复制模板弹窗 -->
    <el-dialog title="复制模板" :visible.sync="copyDialogVisible" width="400px">
      <el-form :model="copyForm" :rules="copyRules" ref="copyForm" label-width="100px">
        <el-form-item label="新模板名称" prop="templateName">
          <el-input v-model="copyForm.templateName" placeholder="请输入新模板名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="copyDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmCopy" :loading="copyLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listHomepageTemplate, addHomepageTemplate, updateHomepageTemplate, delHomepageTemplate, activateTemplate, copyTemplate } from '@/api/home/template'

export default {
  name: 'TemplateManager',
  props: {
    currentCampusId: {
      type: [Number, String],
      default: null
    },
    isAdmin: {
      type: Boolean,
      default: false
    },
    campusList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      // 模板列表
      templateList: [],
      loading: false,
      total: 0,
      selectedTemplates: [],

      // 搜索表单
      searchForm: {
        templateName: '',
        campusId: null,
        pageNum: 1,
        pageSize: 10
      },

      // 保存模板
      saveDialogVisible: false,
      saveLoading: false,
      saveForm: {
        templateName: '',
        templateDesc: '',
        campusId: null
      },
      saveRules: {
        templateName: [
          { required: true, message: '请输入模板名称', trigger: 'blur' }
        ]
      },

      // 复制模板
      copyDialogVisible: false,
      copyLoading: false,
      copyForm: {
        templateName: ''
      },
      copyRules: {
        templateName: [
          { required: true, message: '请输入新模板名称', trigger: 'blur' }
        ]
      },
      currentCopyId: null
    }
  },
  mounted() {
    this.loadTemplateList()
  },
  methods: {
    // 加载模板列表
    async loadTemplateList() {
      this.loading = true
      try {
        const response = await listHomepageTemplate(this.searchForm)
        this.templateList = response.rows || []
        this.total = response.total || 0
      } catch (error) {
        console.error('加载模板列表失败:', error)
        this.$message.error('加载模板列表失败')
      } finally {
        this.loading = false
      }
    },

    // 获取当前编辑器的数据
    getCurrentEditorData() {
      // 从父组件获取当前的页面数据
      return this.$parent.pageComponents && this.$parent.selectedBanners ? {
        components: this.$parent.pageComponents,
        selectedData: {
          banners: this.$parent.selectedBanners,
          entries: this.$parent.selectedEntries,
          goods: this.$parent.selectedGoods,
          recommends: this.$parent.selectedRecommends,
          quicks: this.$parent.selectedQuicks,
          campusAds: this.$parent.selectedCampusAds,
          distributionGoods: this.$parent.selectedDistributionGoods
        }
      } : null
    },

    // 显示保存弹窗
    showSaveDialog() {
      const editorData = this.getCurrentEditorData()
      if (!editorData || !editorData.components || editorData.components.length === 0) {
        this.$message.warning('当前没有可保存的内容')
        return
      }

      this.saveForm = {
        templateName: '',
        templateDesc: '',
        campusId: this.currentCampusId
      }
      this.saveDialogVisible = true
    },

    // 保存模板
    async saveTemplate() {
      this.$refs.saveForm.validate(async (valid) => {
        if (!valid) return

        const editorData = this.getCurrentEditorData()
        if (!editorData) {
          this.$message.error('获取编辑器数据失败')
          return
        }

        this.saveLoading = true
        try {
          const templateData = {
            templateName: this.saveForm.templateName,
            templateDesc: this.saveForm.templateDesc,
            campusId: this.saveForm.campusId,
            templateData: JSON.stringify(editorData)
          }

          await addHomepageTemplate(templateData)
          this.$message.success('模板保存成功')
          this.saveDialogVisible = false
          this.loadTemplateList()
        } catch (error) {
          console.error('保存模板失败:', error)
          this.$message.error('保存模板失败')
        } finally {
          this.saveLoading = false
        }
      })
    },

    // 加载模板
    loadTemplate(template) {
      this.$confirm('确定要加载此模板吗？当前编辑内容将被替换。', '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$emit('load-template', template.templateData)
      }).catch(() => {})
    },

    // 激活模板
    async activateTemplate(template) {
      try {
        await activateTemplate(template.id, template.campusId)
        this.$message.success('模板已激活')
        this.loadTemplateList()
      } catch (error) {
        console.error('激活模板失败:', error)
        this.$message.error('激活模板失败')
      }
    },

    // 复制模板
    copyTemplate(template) {
      this.currentCopyId = template.id
      this.copyForm.templateName = template.templateName + ' (复制)'
      this.copyDialogVisible = true
    },

    // 确认复制
    async confirmCopy() {
      this.$refs.copyForm.validate(async (valid) => {
        if (!valid) return

        this.copyLoading = true
        try {
          await copyTemplate(this.currentCopyId, this.copyForm.templateName)
          this.$message.success('模板复制成功')
          this.copyDialogVisible = false
          this.loadTemplateList()
        } catch (error) {
          console.error('复制模板失败:', error)
          this.$message.error('复制模板失败')
        } finally {
          this.copyLoading = false
        }
      })
    },

    // 删除模板
    deleteTemplate(template) {
      this.$confirm('确定要删除此模板吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await delHomepageTemplate([template.id])
          this.$message.success('删除成功')
          this.loadTemplateList()
        } catch (error) {
          console.error('删除模板失败:', error)
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },

    // 批量删除
    batchDelete() {
      if (this.selectedTemplates.length === 0) {
        this.$message.warning('请选择要删除的模板')
        return
      }

      this.$confirm(`确定要删除选中的 ${this.selectedTemplates.length} 个模板吗？`, '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          const ids = this.selectedTemplates.map(t => t.id)
          await delHomepageTemplate(ids)
          this.$message.success('批量删除成功')
          this.selectedTemplates = []
          this.loadTemplateList()
        } catch (error) {
          console.error('批量删除失败:', error)
          this.$message.error('批量删除失败')
        }
      }).catch(() => {})
    },

    // 获取校区名称
    getCampusName(campusId) {
      if (!campusId) return '通用模板'
      const campus = this.campusList.find(c => c.campusId === campusId)
      return campus ? campus.campusName : '未知校区'
    },

    // 表格选择变化
    handleSelectionChange(selection) {
      this.selectedTemplates = selection
    },

    // 分页
    handleSizeChange(val) {
      this.searchForm.pageSize = val
      this.loadTemplateList()
    },

    handleCurrentChange(val) {
      this.searchForm.pageNum = val
      this.loadTemplateList()
    }
  }
}
</script>

<style scoped>
.template-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.toolbar-left {
  display: flex;
  align-items: center;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.template-list {
  flex: 1;
  overflow: auto;
}

.template-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.batch-operations {
  padding: 10px 15px;
  background: #e3f2fd;
  border-radius: 4px;
  margin-top: 15px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
}

.el-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.el-button-group .el-button {
  padding: 5px 8px;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 10px;
  }

  .toolbar-left {
    width: 100%;
    justify-content: center;
  }

  .el-button-group .el-button span {
    display: none;
  }
}
</style> 